<?php

declare (strict_types=1);

namespace app\controller\admin;

use think\facade\View;
use think\facade\Request;

class Variable extends Common
{
    public function index($act = null)
    {
        if ($act == 'del') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $ids = input('post.ids');
            if (!empty($ids)) {
                foreach ($ids as $k => $v) {
                    unset($this->cyConfig['custom'][$v]);
                }
                $config_file = 'config/cy.php';
                if (!is_writable($config_file)) {
                    return error(lang('请确保config/cy.php文件具有可读写权限'));
                }
                $result = file_put_contents($config_file, "<?php\r\nreturn " . var_export($this->cyConfig, true) . ";");
                if ($result) {
                    add_log('删除自定义变量', $this->request->user->username);
                    return success(lang('操作成功'), (string) url('admin/variable/index'));
                } else {
                    return error(lang('参数错误'));
                }
            }
            return error(lang('请选择需要删除的选项'));
        }

        if ($act == 'edit') {
            $k = input('param.k');
            if (!isset($this->cyConfig['custom'][$k])) {
                return error(lang('参数错误'));
            }
            View::assign('k', $k);
            return View::fetch('form');
        }

        if ($act == 'update') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $k = input('param.k');
            $data = input('post.');

            if ($data['name'] == '') {
                return error(lang('名称不能为空'));
            }
            if ($data['var'] == '') {
                return error(lang('变量名不能为空'));
            }

            $var[$data['var']] =  $data;
            if ($k) {
                unset($this->cyConfig['custom'][$k]);
            } else {
                if (isset($this->cyConfig['custom'][$data['var']])) {
                    return error(lang("变量名已存在：".$data['var']));
                }
            }
            $this->cyConfig['custom'] = array_merge($this->cyConfig['custom'], $var);

            $config_file = 'config/cy.php';
            if (!is_writable($config_file)) {
                return error(lang('请确保config/cy.php文件具有可读写权限'));
            }
            $result = file_put_contents($config_file, "<?php\r\nreturn " . var_export($this->cyConfig, true) . ";");
            if ($result) {
                add_log('新增自定义变量', $this->request->user->username);
                return success(lang('操作成功'), (string) url('admin/variable/index'));
            } else {
                return error(lang('文件写入失败'));
            }
        }

        if ($act == 'add') {
            View::assign('k', false);
            return View::fetch('form');
        }
        return View::fetch();
    }
}
